package com.wjf.birdfish.hibernate;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;

public class PageImplForCriteria<T> extends AbstractPage<T> {
	private PageCriteria criteria;

	protected PageImplForCriteria(Class<T> persistentClass, Session session,
			int pageSize) {
		initialize(session.createCriteria(persistentClass), pageSize);
	}

	protected PageImplForCriteria(Class<T> persistentClass, String alias,
			Session session, int pageSize) {
		initialize(session.createCriteria(persistentClass, alias), pageSize);
	}

	protected PageImplForCriteria(String entityName, Session session,
			int pageSize) {
		initialize(session.createCriteria(entityName), pageSize);
	}

	protected PageImplForCriteria(String entityName, String alias,
			Session session, int pageSize) {
		initialize(session.createCriteria(entityName, alias), pageSize);
	}

	private void initialize(Criteria criteria, int pageSize) {
		this.criteria = new PageCriteria(criteria);
		pageIndex = basePageIndex();
		criteria.setProjection(Projections.rowCount());
		if (pageSize > 0) {
			this.pageSize = pageSize;
		}
		recordNumber = (criteria.list().get(0) == null) ? 0 : Integer.parseInt(criteria.list().get(0).toString());
		setPageNumber();
		criteria.setProjection(null);
	}

	public Criteria getCriteria() {
		return criteria;
	}

	@SuppressWarnings("unchecked")
	public List<T> getData() {
		criteria.setFirstResult(computeFirstResult());
		criteria.setMaxResults(computeMaxResults());
		criteria.applyOrder();
		if (data == null) {
			data = criteria.list();
		}
		return data;
	}

}
